// 本地存储工具函数

// 存储类型
export type StorageType = 'localStorage' | 'sessionStorage'

// 设置存储数据
export const setStorage = <T>(key: string, value: T, storageType: StorageType = 'localStorage'): void => {
  try {
    const storage = window[storageType]
    const data = JSON.stringify(value)
    storage.setItem(key, data)
  } catch (error) {
    console.error('存储数据失败:', error)
  }
}

// 获取存储数据
export const getStorage = <T>(key: string, defaultValue: T | null = null, storageType: StorageType = 'localStorage'): T | null => {
  try {
    const storage = window[storageType]
    const data = storage.getItem(key)
    
    if (data === null) {
      return defaultValue
    }
    
    return JSON.parse(data) as T
  } catch (error) {
    console.error('获取存储数据失败:', error)
    return defaultValue
  }
}

// 删除存储数据
export const removeStorage = (key: string, storageType: StorageType = 'localStorage'): void => {
  try {
    const storage = window[storageType]
    storage.removeItem(key)
  } catch (error) {
    console.error('删除存储数据失败:', error)
  }
}

// 清空所有存储数据
export const clearStorage = (storageType: StorageType = 'localStorage'): void => {
  try {
    const storage = window[storageType]
    storage.clear()
  } catch (error) {
    console.error('清空存储数据失败:', error)
  }
}

// 检查存储是否可用
export const isStorageAvailable = (storageType: StorageType = 'localStorage'): boolean => {
  try {
    const storage = window[storageType]
    const testKey = '__storage_test__'
    storage.setItem(testKey, testKey)
    storage.removeItem(testKey)
    return true
  } catch (error) {
    return false
  }
}

// 获取存储使用情况
export const getStorageInfo = (storageType: StorageType = 'localStorage'): {
  used: number
  total: number
  percentage: number
} => {
  try {
    const storage = window[storageType]
    let used = 0
    
    // 计算已使用空间
    for (let key in storage) {
      if (storage.hasOwnProperty(key)) {
        used += storage[key].length * 2 // 每个字符约2字节
      }
    }
    
    // 估算总空间（通常为5MB）
    const total = 5 * 1024 * 1024
    const percentage = (used / total) * 100
    
    return {
      used,
      total,
      percentage
    }
  } catch (error) {
    console.error('获取存储信息失败:', error)
    return {
      used: 0,
      total: 0,
      percentage: 0
    }
  }
}

// 安全存储用户认证信息
export const setAuthInfo = (token: string, userInfo: any): void => {
  setStorage('token', token)
  setStorage('userInfo', userInfo)
}

// 获取用户认证信息
export const getAuthInfo = (): { token: string | null, userInfo: any | null } => {
  const token = getStorage<string>('token')
  const userInfo = getStorage<any>('userInfo')
  return { token, userInfo }
}

// 清除用户认证信息
export const clearAuthInfo = (): void => {
  removeStorage('token')
  removeStorage('userInfo')
}

// 存储用户首选项
export const setUserPreferences = (preferences: Record<string, any>): void => {
  setStorage('userPreferences', preferences)
}

// 获取用户首选项
export const getUserPreferences = (): Record<string, any> => {
  return getStorage<Record<string, any>>('userPreferences', {}) || {}
}

// 更新用户首选项
export const updateUserPreferences = (key: string, value: any): void => {
  const preferences = getUserPreferences()
  preferences[key] = value
  setUserPreferences(preferences)
}